package com.citycloud.ccuap.tc.admin.role;

import com.citycloud.ccuap.commons.constants.GlobalOperateType;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.model.ISysProject;
import com.citycloud.ccuap.commons.openapi.controller.base.BaseController;
import com.citycloud.ccuap.commons.sys.entity.SysRole;
import com.citycloud.ccuap.commons.sys.repository.SysRoleRepository;
import com.citycloud.ccuap.commons.sys.role.SysRoleDTO;
import com.citycloud.ccuap.commons.web.session.CurrentUser;
import com.citycloud.ccuap.commons.web.util.ResolveRequest;
import com.citycloud.ccuap.framework.exception.ApplicationException;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.framework.util.StringUtil;
import com.citycloud.ccuap.tc.admin.datagroup.IDatagroupService;
import com.citycloud.ccuap.tc.admin.entity.SysDatagroup;
import com.citycloud.ccuap.tc.admin.sec.secuser.SecUserCacheService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.springframework.data.domain.Sort.Direction.ASC;

/**
 * @author liujw
 * @create 2019-06-28 11:30
 * Description:
 */

@RestController
@RequestMapping("/v1/yq/sys/roleApi")
@Api(tags = "站点角色控制类", value = "站点角色控制类--RoleApiController")
public class RoleApiController extends BaseController {

    @Autowired
    SysRoleRepository roleApiRepository;

    @Autowired
    RoleApiService roleApiService;



    @Autowired
    IDatagroupService dataGroupService;
    
    @Autowired
    SecUserCacheService secUserCacheService;

    private static final String ROLE_CODE_PREFIX = "role_";

    private static final String SITE_ROLE_CODE_PREFIX = "site_role_";

    /**
     * 查询当前角色下的所有数据组
     *
     * @return
     * @throws Exception
     */
    @ApiOperation("查询当前角色下的所有数据组")
    @RequestMapping(value = "/getByRoleId", method = {RequestMethod.POST})
    public JSONData getByRoleId() throws Exception {
        List<SysDatagroup> list = dataGroupService.getByRoleId(getLongParameter("roleId"));
        JSONData jsonData = new JSONData(list);
        return jsonData;
    }

    /**
     * 管理员获取角色列表
     * (平台管理员都只能看到自己创建的角色)
     * (站点管理员只能看到站点下的角色同时要排除平台管理员创建的)
     *
     * @return
     * @throws Exception
     */
    @ApiOperation("根据条件查询对象")
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData query() throws Exception {
        PageQuery<Map<String, Object>> pageQuery = ResolveRequest.getPageForParams(request);
        SysRoleDTO sysRoleDTO = new SysRoleDTO();
        ResolveRequest.fillData(request, sysRoleDTO, "q_", true);
        Long projectId = getProjectId();
        PageQuery<Map<String, Object>> pageData;
        String orderFieldName = getStringParameter("q_orderByFieldName");
        if (!StringUtils.isEmpty(orderFieldName)) {
            String orderType = getStringParameter("q_orderByType", ASC.name()).toUpperCase();
            pageData = roleApiService.findByNameAndProId(pageQuery, sysRoleDTO.getRoleName(),
                    sysRoleDTO.getRoleId(), projectId, StringUtil.getDBFieldName(orderFieldName), orderType, false);
        } else {
            pageData = roleApiService.findByNameAndProId(pageQuery, sysRoleDTO.getRoleName(),
                    sysRoleDTO.getRoleId(), projectId, false);
        }
        JSONData jsonData = new JSONData(pageData);
        return jsonData;
    }

    /**
     * 站点角色管理
     * (平台管理员都只能看到自己创建的站点角色)
     *
     * @return
     * @throws Exception
     */
    @ApiOperation("根据条件查询对象")
    @RequestMapping(value = "/getDataTables", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getDataTables() throws Exception {
        PageQuery<Map<String, Object>> pageQuery = ResolveRequest.getPageForParams(request);
        SysRoleDTO sysRoleDTO = new SysRoleDTO();
        ResolveRequest.fillData(request, sysRoleDTO, "q_", true);
        Long projectId = getProjectId();
        PageQuery<Map<String, Object>> pageData;
        String orderFieldName = getStringParameter("q_orderByFieldName");

        if (!StringUtils.isEmpty(orderFieldName)) {
            String orderType = getStringParameter("q_orderByType", ASC.name()).toUpperCase();
            pageData = roleApiService.findByNameAndProId(pageQuery, sysRoleDTO.getRoleName(),
                    sysRoleDTO.getRoleId(), projectId, StringUtil.getDBFieldName(orderFieldName), orderType, true);
        } else {
            pageData = roleApiService.findByNameAndProId(pageQuery, sysRoleDTO.getRoleName(),
                    sysRoleDTO.getRoleId(), projectId, true);
        }

        JSONData jsonData = new JSONData(pageData);
        return jsonData;
    }


    /**
     * 平台管理员新增角色对象
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新增角色对象", notes = "save")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public JSONData save() throws Exception {
        SysRole sysRole = getRequestDataObject(GlobalOperateType.ADD);
        int roleCount = 0;
        if (this.getProjectId() == null) {
            roleCount = roleApiRepository.countByRoleCode(sysRole.getRoleCode());
        } else {
            roleCount = roleApiRepository.countByRoleCodeAndProjectId(sysRole.getRoleCode(), this.getProjectId());
        }

        if (roleCount > 0) {
            throw new ApplicationException("角色编码不能重复！");
        } else {
            roleApiService.save(sysRole);
            JSONData jsonData = new JSONData("添加角色信息成功！");
            return jsonData;
        }
    }

    @ApiOperation(value = "更新对象", notes = "update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JSONData update() throws Exception {
        SysRole sysRole = getRequestDataObject(GlobalOperateType.EDIT);

        SysRole existSysRole = roleApiService.findById(sysRole.getRoleId());
        if (!existSysRole.getRoleCode().equals(sysRole.getRoleCode())) {
            int roleCount = 0;
            if (getProjectId() == null) {
                roleCount = roleApiRepository.countByRoleCode(sysRole.getRoleCode());
            } else {
                roleCount = roleApiRepository.countByRoleCodeAndProjectId(sysRole.getRoleCode(), getProjectId());
            }
            if (roleCount > 0) {
                throw new Exception("角色编码不能重复！");
            }
        }
        roleApiService.updateRole(sysRole);
        if(sysRole.getDataStatus() == 1){
            secUserCacheService.buildRoleDataGroupCache(sysRole.getRoleId());
        } else{
            secUserCacheService.deleteRoleDataGroupCache(sysRole.getRoleId());
        }

        JSONData jsonData = new JSONData("修改角色信息成功！");
        return jsonData;
    }

    @ApiOperation(value = "保存或更新对象，一般用于表格数据的编辑", notes = "saveAndUpdate")
    @RequestMapping(value = "/saveAndUpdate", method = RequestMethod.POST)
    public JSONData saveAndUpdate() throws Exception {
        SysRole sysRole = getRequestDataObject(GlobalOperateType.EDIT);
        roleApiService.save(sysRole);
        JSONData jsonData = new JSONData("修改角色信息成功！");
        return jsonData;
    }

    /**
     * 获取页面提交的对象
     *
     * @return struts result
     * @throws Exception
     */
    private SysRole getRequestDataObject(short operateType) throws Exception {
        SysRole sysRole = new SysRole();
        ResolveRequest.fillData(request, sysRole);

        String json = ResolveRequest.getJsonByPrefix(request, "json");
        sysRole.setJson(json);

        CurrentUser user = getCurrentUser();
        logger.debug("RoleApiController 中 save方法 user 信息：{}", user);
        if (GlobalOperateType.ADD == operateType) {
            ISysProject sysProject = user.getProject();
            if (sysProject != null) {
                sysRole.setProjectId(sysProject.getProjectId());
            }
            sysRole.setCreator(user.getUser().getUserNo());
            sysRole.setCreatedTime(new Date());
            if(StringUtils.isBlank(sysRole.getRoleCode())){
                String code = UUID.randomUUID().toString().replaceAll("-","");
                if(sysRole.getProjectId() != null){
                    //  编码 SITE_ROLE_CODE_PREFIX
                    sysRole.setRoleCode(SITE_ROLE_CODE_PREFIX + code);
                }else{
                    //  编码 ROLE_CODE_PREFIX
                    sysRole.setRoleCode(ROLE_CODE_PREFIX + code);
                }
            }
        } else if (GlobalOperateType.EDIT == operateType) {
            sysRole.setUpdator(user.getUser().getUserNo());
            sysRole.setUpdatedTime(new Date());
        }

        return sysRole;
    }

    @ApiOperation(value = "站点级权限新增角色对象", notes = "insert")
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public JSONData insert() throws Exception {
        SysRole sysRole = this.getRequestDataObject(GlobalOperateType.ADD);
        this.roleApiService.insert(sysRole);
        JSONData jsonData = new JSONData("添加角色信息成功！");
        return jsonData;

    }

    private String getRoleCount(SysRole sysRole,String uuidCode) {
        int roleCount=0;
        String rolecode=uuidCode;
        if (this.getProjectId() == null) {
            roleCount = this.roleApiRepository.countByRoleCode(sysRole.getRoleCode());
        } else {
            roleCount = this.roleApiRepository.countByRoleCodeAndProjectId(sysRole.getRoleCode(), this.getProjectId());
        }
        if(roleCount>0){
            rolecode=UUID.randomUUID().toString().replaceAll("-","");
            getRoleCount(sysRole,rolecode);
        }
        return rolecode;
    }
}


